package sicnu.cs.ich.common.interceptor.rest;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;
import sicnu.cs.ich.api.common.annotations.rest.DecryptBody;
import sicnu.cs.ich.common.services.impl.RedisService;
import sicnu.cs.ich.common.util.keyCryptor.AESUtil;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Objects;

import static sicnu.cs.ich.api.common.Constants.REDIS_AES_KEY;


/**
 * @author CaiKe
 * @date 2021/11/3 19:10
 */

@Slf4j
@ControllerAdvice
@Order(1)
@RequiredArgsConstructor
@RefreshScope
public class SecretRequestAdvice extends RequestBodyAdviceAdapter {

    private final RedisService redisService;

    @Value("${ich.decrypt.enabled:false}")
    private Boolean enabled;

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    /**
     * 是否支持加密消息体
     *
     * @param methodParameter methodParameter
     * @return true/false
     */
    private boolean supportSecretRequest(MethodParameter methodParameter) {
        if (!enabled) {
            return false;
        }
//        //判断class是否存在解密注解
//        if (methodParameter.getContainingClass().getAnnotation(DecryptBody.class) != null) {
//            return true;
//        }
        //判断方法是否存在注解
        return methodParameter.getMethodAnnotation(DecryptBody.class) != null;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        //如果支持加密消息，进行消息解密。
        boolean supportSafeMessage = supportSecretRequest(parameter);
        String httpBody;
        if (supportSafeMessage) {
            httpBody = decryptBody(inputMessage);
            if (httpBody == null) {
                throw new HttpMessageNotReadableException("request body decrypt error");
            }
        } else {
            httpBody = StreamUtils.copyToString(inputMessage.getBody(), Charset.defaultCharset());
        }
        //返回处理后的消息体给messageConvert
        return new SecretHttpMessage(new ByteArrayInputStream(httpBody.getBytes()), inputMessage.getHeaders());
    }

    /**
     * 解密消息体,3des解析（cbc模式）
     *
     * @param inputMessage 消息体
     * @return 明文
     */
    private String decryptBody(HttpInputMessage inputMessage) throws IOException {
        InputStream encryptStream = inputMessage.getBody();
        String encryptBody = StreamUtils.copyToString(encryptStream, Charset.defaultCharset());
        val key = (String) redisService.getValue(REDIS_AES_KEY);
        Objects.requireNonNull(key);
        return AESUtil.decode(key, encryptBody);
    }

}